package walletuserslogic

import (
	"context"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/uniqueid"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserCreateTransferFromGameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserCreateTransferFromGameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserCreateTransferFromGameLogic {
	return &UserCreateTransferFromGameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建转入B端钱包
func (l *UserCreateTransferFromGameLogic) UserCreateTransferFromGame(in *pb.UserCreateTransferFromGameReq) (*pb.UserCreateTransferFromGameResp, error) {
	defer utils.RecoverPanic()

	var err error
	// 查询用户转账流水
	var utfCnt int64
	utfCnt, err = l.svcCtx.UserTransferFromGameFlowModel.CountByState(l.ctx, in.Uid, in.ProviderId, in.MoneyType, walletkey.UserWalletTransferFromGameFlowStateInit)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	// 判断是否已经存在初始状态转账流水
	if utfCnt > 0 {
		l.Logger.Errorf("err == ", zap.Error(xerr.NewGrpcErrCodeMsg(xerr.WalletFlowStateNotAllow, "transfer in processing")))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletFlowStateNotAllow, "transfer in processing")
	}

	//
	var dMoneyAmount decimal.Decimal
	dMoneyAmount, err = decimal.NewFromString(in.MoneyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	iMoneyAmount := dMoneyAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale)).IntPart()
	// 创建用户转账流水
	utf := wallet.UserTransferFromGameFlow{
		FlowNo:      uniqueid.GenFlowNoX(),
		Uid:         in.Uid,
		ProviderId:  in.ProviderId,
		MoneyType:   in.MoneyType,
		MoneyAmount: iMoneyAmount,
		State:       walletkey.UserWalletTransferFromGameFlowStateInit,
	}

	_, err = l.svcCtx.UserTransferFromGameFlowModel.Insert(l.ctx, &utf)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	return &pb.UserCreateTransferFromGameResp{FlowNo: utf.FlowNo}, nil
}
